package com.hhkj.admin.common.aspectj;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.hhkj.admin.common.annotation.UseRedis;
import com.ruoyi.common.core.redis.RedisCache;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Aspect
@Component
public class UseRedisAspect {

    @Autowired
    private RedisCache redisCache;

    private static final Logger logger = LoggerFactory.getLogger(UseRedisAspect.class);

    /**
     * 先读redis，没有的话，走方法，将返回值存redis。有的话直接返回
     * @param joinPoint
     * @param useRedis
     * @return
     */
    @Around(value = "@annotation(useRedis)")
    public Object around(ProceedingJoinPoint joinPoint, UseRedis useRedis) {
        String title = useRedis.value();
        Class clazz = useRedis.clazz();
        int timeout = useRedis.timeout();
        TimeUnit timeUnit = useRedis.timeUnit();
        Object result = null;
        //前缀格式统一
        if (title.endsWith(":") == false) {
            title = title + StrUtil.COLON;
        }
        //生成key
        String key = title + clazz.getSimpleName();
        try {
            //先查缓存
            result = redisCache.getCacheObject(key);
            if (ObjectUtil.isNotEmpty(result)) {
                //缓存有就直接返回
                return result;
            }
            //缓存没有就走方法
            result = joinPoint.proceed();
            //存入缓存
            if(ObjectUtil.isNotEmpty(result)) {
                redisCache.setCacheObject(key, result, timeout, timeUnit);
            }
            return result;
        } catch (Exception e) {
            logger.info(e.getMessage());
        } catch (Throwable e) {
            logger.info(e.getMessage());
        } finally {
            return result;
        }
    }
}
